import type { Ref } from 'vue'
import { defineStore } from 'pinia'
import router from '@/router'
import {
  transformAsyncMenus,
  getHomeRoute,
  getBreadCrumbList,
} from '@/util/common'
import type { Routers } from '@/router/defaultRoute'


export type MenuList = Routers & {
  _id: string,
  title: string | string[]
  icon: string
  enable: boolean
  sort: number
  menu_id: string
  parent_id?: string
  comment?: string
  [key: string]: any; // 允许其他字段存在
}

export interface MenuState {
  menuList: Ref<MenuList[]>
  setMenuList: (menus: MenuList[]) => void
  isCollapse: Ref<boolean>
  changeIsCollapse: (val: boolean) => void
  openeds: Ref<any[]>
  setOpeneds: (value: any[]) => void
  activeName: Ref<any>
  setActiveName: (name: string) => void
  setBreadCrumb: (to: any, route: any[]) => void
  brendCrumbList: Ref<any[]>
}
export const useMenuStore = defineStore(
  'menu',
  (): MenuState => {
    const menuList: MenuState['menuList'] = ref([])

    const setMenuList: MenuState['setMenuList'] = menus => {
      menuList.value = menus

      router.addRoute({
        path: '/',
        component: () => import('@/layout/Main.vue'),
        children: transformAsyncMenus(menuList.value),
      })
      // console.log('添加完', router.getRoutes())
    }

    const isCollapse: MenuState['isCollapse'] = ref(true)
    const changeIsCollapse: MenuState['changeIsCollapse'] = (val: boolean) => {
      isCollapse.value = !isCollapse.value
    }

    const openeds: MenuState['openeds'] = ref<any>([])
    const setOpeneds: MenuState['setOpeneds'] = value => {
      openeds.value = value
    }

    const brendCrumbList: MenuState['brendCrumbList'] = ref<any[]>([])
    const setBreadCrumb: MenuState['setBreadCrumb'] = (to, route) => {
      const homeItem = getHomeRoute(route)
      const BreadCrumbList = getBreadCrumbList(to, homeItem)
      brendCrumbList.value = BreadCrumbList
    }

    const activeName: MenuState['activeName'] = ref()
    const setActiveName: MenuState['setActiveName'] = name => {
      activeName.value = name
    }
    return {
      menuList,
      setMenuList,
      isCollapse,
      changeIsCollapse,
      openeds,
      setOpeneds,
      activeName,
      setActiveName,
      setBreadCrumb,
      brendCrumbList,
    }
  },
  {
    persist: true,
  },
)
